package ctgu.java;

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.nio.charset.StandardCharsets; 
import java.util.Properties;
import java.text.*;
import java.util.Date;


public class Configuration {
	private Properties props = new Properties();
	/**
	 * 读取属性配置文件
	 * 
	 * @param confFile
	 */
	public void fromFile(File confFile) {
		try(FileInputStream in = new FileInputStream(confFile);){
			props.load(new InputStreamReader(in,StandardCharsets.UTF_8));
		} catch (IOException e) {
			throw new ValueParseException("配置文件解析错误");
		} 
	}
	/**
	 * 获取键值
	 * 
	 * @param key
	 * @return value
	 */
	public String getProp(String key) {
		return props.getProperty(key);
	}
	/**
	 * 获取布尔类型键值
	 * 
	 * @param key
	 * @return value
	 */
	public boolean getBoolean(String key) {
		String value = props.getProperty(key);
		if ("true".equalsIgnoreCase(value)) {
			return true;
		}
		if ("false".equalsIgnoreCase(value)) {
			return false;
		}
		throw new ValueParseException("键值不存在");
	}
	
	public Boolean getBooleanWithDefault(String key, Boolean defaultValue) {
		
			String value = props.getProperty(key);
			if ("true".equalsIgnoreCase(value)) {
				return true;
			}
			if ("false".equalsIgnoreCase(value)) {
				return false;
			}
			return defaultValue;
	}
	
	public Integer getInt(String key, int defaultValue) {
		String value = props.getProperty(key);
		if(value != null) {
			int int_value = Integer.parseInt(value);
		    return int_value;
		    }
		else return defaultValue;
	}
	
	public Date getDate(String key, Date defaultValue) {
		String value = props.getProperty(key);
		if(value != null) {
			    try{
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				Date Date_value = formatter.parse(value);
				return Date_value;
				}catch (ParseException e) {
					return defaultValue;
			} 
		}
		else return defaultValue;
	}
	
	

}